import translateItem from './translateItem';
import util from '../util';

class file {
  //文件名
  private fileName: string;
  //文件后缀
  private fileType: string;
  //文件内容
  private fileContent: Map<string, translateItem>;
  //最后修改时间
  private fileLastEditDate!: string;
  constructor(
    fileName: string,
    fileType: string,
    fileContent: translateItem[]
  ) {
    this.fileName = fileName;
    this.fileType = fileType;
    this.fileContent = this.fileContentDo(fileContent);
  }
  // ?
  private fileContentDo(value: translateItem[]): Map<string, translateItem> {
    let m = new Map<string, translateItem>();
    value.forEach(e => {
      m.set(e.getItemKey(), e);
    });
    return m;
  }
  // ?
  public getMap(): Map<string, translateItem> {
    return this.fileContent;
  }
  /**
   * 获取文件名称
   */
  public getFileName(): string {
    return this.fileName;
  }
  /**
   * 获取文件类型
   */
  public getFileType(): string {
    return this.fileType;
  }
  /**
   * 获取文件内容
   */
  public getFileContent(): translateItem[] {
    let value: translateItem[] = [];
    this.fileContent.forEach(v => {
      value.push(v);
    });
    return value;
  }
  /**
   * 获取完成百分比
   * @returns {number} 0.0——1
   */
  public getPercentComplete(): number {
    let complete = 0;
    this.fileContent.forEach(v => {
      if (v.getIsComplete()) {
        complete++;
      }
    });
    return complete / this.getFileSize();
  }
  /**
   * 获取词条数目
   */
  public getFileSize(): number {
    return this.fileContent.size;
  }
  /**
   * 添加词条
   */
  public addContent(value: translateItem) {
    this.fileContent.set(value.getItemKey(), value);
  }
  public addContents(value: translateItem[]) {
    value.forEach(e => {
      this.addContent(e);
    });
  }
  /**
   * 对比词条
   */
  public equals(value: file): boolean {
    let length = this.getFileSize();
    if (length === value.getFileSize()) {
      for (let i = 0; i < length; i++) {
        if (
          this.getFileContent()[i].getItemKey() !==
            value.getFileContent()[i].getItemKey() ||
          this.getFileContent()[i].getRawText() !==
            value.getFileContent()[i].getRawText()
        ) {
          return false;
        }
      }
      return true;
    } else {
      return false;
    }
  }
  /**
   * 更新最后修改时间
   */
  public upEditDate() {
    this.fileLastEditDate = util.getNowDate();
  }
  /**
   * 更新词条
   */
  public update(value: file): translateItem[] {
    let length = value.getFileSize();
    let newTranslateItem: translateItem[] = [];
    for (let i = 0; i < length; i++) {
      if (this.getMap().has(value.getFileContent()[i].getItemKey()) === false) {
        newTranslateItem.push(value.getFileContent()[i]);
      }
    }
    this.upEditDate();
    return newTranslateItem;
  }
}

export default file;
